<?php

if (! defined ( 'BASEPATH' ))
	exit ( 'No direct script access allowed' );
class Detial extends CI_Controller {
	
	const SINA          = 'sina';
	const YUNYUN        = 'yunyun';
	const NETEASE       = 'netease';
	const SOHU          = 'sohu';
	const TENCENT       = 'tencent';
	const PLATFORM      = 'platform';
	const ADMIN         = 'soften';
	const ERROR_TAB     = 'error';
	const LOG_LEVEL_ERROR = 'error';
	const LOG_LEVEL_WARING = 'waring';
	const LOG_LEVEL_NOTICE = 'notice';
	public $_log_dir    = 'keyword';
	public $_result_dir = 'result';
	public $_return_data;
	
	public function __construct(){
		parent::__construct();
		$this->load->helper('MY_auth_verification');
		$this->load->library('error_code_library');
		$this->load->library('crawl_abstract');
		//$this->load->database();
		$this->_return_data = $this->config->item('return_data');
	}
	
	
	
	function detail() {
		
		$auth_verification_result = authentication($this, $this->input->post());
		if(is_array($auth_verification_result) && array_key_exists(self::ERROR_TAB, $auth_verification_result)) {
			echo json_encode($auth_verification_result);
			exit;
		} else {
			$this->crawl();
		}		
	}
	
	function test() {
		
    	// 这里是模拟一次请求　也就是测试index方法是否正确
    	$post_data=$this->input->post();
    	header('Content-Type:text/html;charset=utf-8');            
    		   	
    	$post_data['platform'] = "sina";
    	$post_data['url']=$this->input->post('url');
    	$post_data['token'] = "9f7ffa5b38e13b1843eeffcc3ba06565";

    	$url=site_url('detial/crawl') ;
    	$ch=curl_init($url);
    	curl_setopt($ch,CURLOPT_POST,1) ;
    	curl_setopt($ch,CURLOPT_RETURNTRANSFER,true) ;
    	curl_setopt($ch, CURLOPT_HEADER, 0);
    	curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
    	
    	$result =curl_exec($ch);

    	$result = json_decode($result,TRUE);
    	
    	echo "<pre>" ;
    	
    	print_r($result);
    	
    	echo "</pre>" ;
		
	}
	
	
	public function crawl() {
		header ( 'Content-Type:text/html;charset=utf-8' );		
		//这里执行抓取程序并返回结果
		$this->load->library('crawl_keyword_library');
		$this->load->library('Crawl_sina_weibo_detial_library');

		$result = $this->crawl_sina_weibo_detial_library->crawl(FALSE);
				 
		if( is_null($result) || array_key_exists(self::ERROR_TAB, $result) == FALSE) {
			if(array_key_exists('data', $result)) {
				$result_string = json_encode($this->_return_data);
			} else {
				$this->_return_data['data'] = $result;
				$result_string = json_encode($this->crawl_keyword_library->return_utf8_code($this->_return_data));
			}
	
			log_message(self::LOG_LEVEL_NOTICE, 'Return Result Crawl String: '.$result_string, FALSE, $this->_result_dir);
	
			echo $result_string;
		} else {
			$this->_return_data['error'] = $result;
			log_message(self::LOG_LEVEL_ERROR, 'Crawl Error: '.json_encode($this->crawl_keyword_library->return_utf8_code($this->_return_data)), FALSE, $this->_log_dir);
			echo json_encode($this->_return_data);
		}
	}
	
}